﻿using CdhpyScheduler.Core;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;

namespace CdhpyScheduler.WebHost.PubMethod
{
    public class Job
    {
        public static ScheduleCenter jc = new ScheduleCenter();

        /// <summary>
        /// Load jobs from confing file
        /// </summary>
        /// <returns></returns>
        public static List<JobModel> LoadJobFromFile()
        {
            string filePath = AppDomain.CurrentDomain.BaseDirectory + "\\Config\\HTTP_Job_List.json";
            string content = string.Empty;
            using (var stream = new System.IO.StreamReader(System.IO.Path.GetFullPath(filePath), Encoding.UTF8))
            {
                content = stream.ReadToEnd();
            }

            List<JobModel> jobs = new List<JobModel>();
            try
            {
                var dyn = JsonConvert.DeserializeObject<dynamic>(content);
                jobs = ((Newtonsoft.Json.Linq.JArray)dyn).ToObject<List<JobModel>>();
            }
            catch 
            {
                throw;
            }
            return jobs;
        }

        /// <summary>
        /// Overwrite job config file
        /// </summary>
        /// <returns></returns>
        public static void OverwriteJobFile(List<JobModel> jobs)
        {
            string filePath = AppDomain.CurrentDomain.BaseDirectory + "\\Config\\HTTP_Job_List.json";
            string content = JsonConvert.SerializeObject(jobs);
            File.WriteAllText(filePath, content);
        }
    }
}